package com.ytjj.qmyx.admin.controller.channelProductController;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.utils.HttpClientUtil;
import com.ytjj.qmyx.admin.annotation.OperLog;
import com.ytjj.qmyx.admin.annotation.oplog.OperationProductLogger;
import com.ytjj.qmyx.admin.annotation.oplog.annotation.OperationLog;
import com.ytjj.qmyx.admin.config.SupplyApiConfig;
import com.ytjj.qmyx.admin.constants.SysLogConstants;
import com.ytjj.common.constants.PlatformConstant;
import com.ytjj.qmyx.admin.model.ProductSelectDetailResponse;
import com.ytjj.qmyx.admin.model.PutOutProductResp;
import com.ytjj.qmyx.admin.model.SalesChannelsManagement;
import com.ytjj.qmyx.admin.model.request.ChannelProductRequest;
import com.ytjj.qmyx.admin.model.request.ProductChannelRequest;
import com.ytjj.qmyx.admin.model.request.PutOutChannelProductRequest;
import com.ytjj.qmyx.admin.model.request.channel.ChannelGoodsRequest;
import com.ytjj.qmyx.admin.model.request.channel.ChannelProductSelectRequest;
import com.ytjj.qmyx.admin.model.response.AreaChannelsManagementResponse;
import com.ytjj.qmyx.admin.model.response.AreaProductChannelResponse;
import com.ytjj.qmyx.admin.service.GoodsService;
import com.ytjj.qmyx.admin.service.channelProductService.ChannelProductService;
import com.ytjj.qmyx.mall.model.Product;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 * 销售渠道商品 管理
 */
@RestController
@RequestMapping("/channelProduct")
@Slf4j
public class ChannelProductController {

    @Resource
    private ChannelProductService channelProductService;
    @Resource
    private GoodsService goodsService;

    @Autowired
    private SupplyApiConfig supplyApiConfig;



    /**
     * 条件获取销售渠道商品信息------------app
     * @param request
     * @return
     */
    @PostMapping("/ProductChannelList")
    public CommonResult appProductChannelList(@RequestBody ProductChannelRequest request) {
//        request.setPlatformData("app");
        return channelProductService.productChannelList(request);
    }

    /**
     * 条件获取地区销售渠道地区全部商品---地区销售渠道
     * @param request
     * @return
     */
    @PostMapping("/areaProductChannelList")
    public CommonResult<List<AreaProductChannelResponse>> areaProductChannelList(@RequestBody ProductChannelRequest request) {
        return channelProductService.areaProductChannelList(request);
    }

    /**
     * 条件获取销售渠道商品信息------------h5
     * @param request
     * @return
     */
    @PostMapping("/h5ProductChannelList")
    public CommonResult h5ProductChannelList(@RequestBody ProductChannelRequest request) {
        request.setPlatformData("h5");
        return channelProductService.productChannelList(request);
    }

    /**
     * 从销售渠道中移除商品-----------app
     * @param productChannelId
     * @return
     */
    @GetMapping("/removeProduct")
    @OperLog(operModule = SysLogConstants.PRODUCT, operType = SysLogConstants.PRODUCT_DOWN, operDesc = "APP商品下架")
    public CommonResult removeProduct(@RequestParam Integer productChannelId) {
        return channelProductService.removeProduct(productChannelId);
    }

    /**
     * 从销售渠道中移除商品-----------h5
     * @param productChannelId
     * @return
     */
    @GetMapping("/removeH5Product")
    @OperLog(operModule = SysLogConstants.PRODUCT, operType = SysLogConstants.PRODUCT_DOWN, operDesc = "H5商品下架")
    public CommonResult removeH5Product(@RequestParam Integer productChannelId) {
        return channelProductService.removeH5Product(productChannelId);
    }

    /**
     * 从地区销售渠道中移除商品
     * @param productChannelId 商品id
     * @param isMain 是否是主商品 1-是主商品； 其他值-是子商品
     * @return
     */
    @GetMapping("/removeProductFromArea")
    @OperLog(operModule = SysLogConstants.PRODUCT, operType = SysLogConstants.PRODUCT_MOVE, operDesc = "移除商品地区商品")
    public CommonResult removeProductFromArea(@RequestParam Integer productChannelId,Integer isMain) {
        return channelProductService.removeProductFromArea(productChannelId,isMain);
    }

    /**
     * app渠道商品详细
     * @param productId
     * @return
     */
    @GetMapping("/getProductChannelInfo/{productId}")
    public CommonResult getProductChannelInfo(@PathVariable Integer productId) {
        return channelProductService.getProductChannelInfo(productId);
    }

    /**
     * 编辑商品详情信息--app渠道
     * @param goodsRequest
     * @return
     */
    @PostMapping("/updateGoods")
    @OperationLog(optModule = SysLogConstants.PRODUCT, optType = SysLogConstants.OPERATION_UPDATE, desc = "编辑商品详情信息")
    public CommonResult updateGoods(@Validated @RequestBody ChannelGoodsRequest goodsRequest) {
        goodsService.updateGoods(goodsRequest);
        return CommonResult.success();
    }

//    /**
//     * 编辑商品详情信息--地区销售渠道
//     * @param goodsRequest
//     * @return
//     */
//    @PostMapping("/updateGoodsForProvince")
//    @OperationLog(optModule = SysLogConstants.PRODUCT, optType = SysLogConstants.OPERATION_UPDATE, desc = "编辑商品详情信息--地区销售渠道")
//    public CommonResult updateGoodsForProvince(@Validated @RequestBody ChannelGoodsRequest goodsRequest) {
//        goodsService.updateGoods(goodsRequest);
//        return CommonResult.success();
//    }

    /**
     * 供应链促使销售端商品下架
     * @param bankerProductIds
     * @return
     */
    @GetMapping("/updateGoodsStatusByRpc")
    @OperationLog(optModule = SysLogConstants.PRODUCT, optType = SysLogConstants.PRODUCT_DOWN, desc = "供应链促使销售端商品下架")
    public CommonResult updateGoodsStatusByPrc(String bankerProductIds) {
        log.info("===供应链促使销售端商品下架==={}", bankerProductIds);
        goodsService.updateGoodsStatusByPrc(bankerProductIds);
        return CommonResult.success();
    }

    /**
     * 销售渠道 - 商品 -上下架----------App
     * @return
     */
    @PostMapping(value = "/putOutChannelProduct")
    @OperationLog(optModule = SysLogConstants.PRODUCT, optType = SysLogConstants.OPERATION_UPDATE, desc = "销售渠道商品上架/下架")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult putOutChannelProduct(@RequestBody ChannelProductRequest product) {
        try {
            if (StringUtils.isNotBlank(product.getPlatformData()) && null != product.getSupplyProductId()) {
                if("all".equals(product.getPlatformData())) {
                    //all不包括地区渠道
                    List<String> platformDatas = Arrays.asList(PlatformConstant.APP_PLATFORM, PlatformConstant.H5_2_PLATFORM, PlatformConstant.PLATFORM_H5, PlatformConstant.H5_3_PLATFORM);
                    List<Product> channelProducts = channelProductService.queryBySupplyIdAndPlatformData(Lists.newArrayList(product.getSupplyProductId()),platformDatas);
                    PutOutProductResp putOutProductResp = channelProductService.batchPutOutChannelProduct(channelProducts, product.getStatus());
                    if (!CollectionUtils.isEmpty(putOutProductResp.getFailProduts())) {
                        List<String> collect = putOutProductResp.getFailProduts().stream().map(e -> "商品id：" + e.getId() + "," + e.getFailRemark()).collect(Collectors.toList());
                        return CommonResult.failed(collect.toString());
                    }
                    return CommonResult.success();
                }
                //选择地区销售渠道同步上架
                else if(PlatformConstant.PROVINCE_PLATFORM.equals(product.getPlatformData())) {
                    List<String> provinceCodes = Optional.ofNullable(product.getProvinceCodes()).orElse(new ArrayList<>());
                    if(CollectionUtils.isEmpty(provinceCodes)){
                        throw new ApiException("请选择对应地区再操作！");
                    }
                    List<String> areaPlatform = new ArrayList<>();
                    for (String provinceCode : provinceCodes) {
                        areaPlatform.add(PlatformConstant.PROVINCE_PLATFORM + provinceCode);
                    }
                    List<Product> channelPro = channelProductService.queryBySupplyIdAndPlatformData(Lists.newArrayList(product.getSupplyProductId()),areaPlatform);
                    List<Product> channelProducts = channelPro.stream().filter(e -> !PlatformConstant.PROVINCE_PLATFORM.equals(e.getPlatformData())).collect(Collectors.toList());
                    PutOutProductResp putOutProductResp = channelProductService.batchPutOutChannelProduct(channelProducts, product.getStatus());
                    if (!CollectionUtils.isEmpty(putOutProductResp.getFailProduts())) {
                        List<String> collect = putOutProductResp.getFailProduts().stream().map(e -> "商品id：" + e.getId() + "," + e.getFailRemark()).collect(Collectors.toList());
                        return CommonResult.failed(collect.toString());
                    }
                    return CommonResult.success();
                }
                //否则上架单独选的渠道
                List<Product> channelProducts = channelProductService.queryBySupplyIdAndPlatformData(Lists.newArrayList(product.getSupplyProductId()), Arrays.asList(product.getPlatformData()));
                if (!CollectionUtils.isEmpty(channelProducts)) {
                    product.setProductChannelId(channelProducts.get(0).getId());
                }
            }
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", product.getProductChannelId());
            map.put("batch", 0);
            if (product.getStatus().equals(1)) {
                map.put("msg", "商品上架");
            } else if (product.getStatus().equals(2)) {
                map.put("msg", "商品下架");
            } else if (product.getStatus().equals(3)){
                map.put("msg", "商品移除");
            } else {
                map.put("msg", "销售渠道商品上架/下架/移除");
            }
            OperationProductLogger.log(map);
        } catch (Exception e) {
            log.error("拼装销售渠道商品上架/下架/移除日志信息异常{}", e);
            throw new ApiException("拼装销售渠道商品上架/下架/移除日志信息异常:"+e.getMessage());
        }
        return channelProductService.putOutChannelProduct(product.getProductChannelId(),product.getStatus(),product.getOutRemarks());
    }

    @PostMapping(value = "/batchPutOutChannelProduct")
    @OperationLog(optModule = SysLogConstants.PRODUCT, optType = SysLogConstants.OPERATION_UPDATE, desc = "商品批量上架/下架")
    public CommonResult batchPutOutChannelProduct(@RequestBody PutOutChannelProductRequest request) {
        Assert.notNull(request.getProducts(), "商品不能为空!");
        String platformData = request.getPlatformData();
        if (StringUtils.isNotBlank(platformData) && !CollectionUtils.isEmpty(request.getProducts())) {
            List<Integer> supplyProductIds = request.getProducts().stream().map(Product::getSupplyProductId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(supplyProductIds)) {
                //选择的渠道集合
                List<String> platformDataList = new ArrayList<>();
                //此处的全部不包括地区销售渠道
                if("all".equals(platformData)){
                    platformDataList = Arrays.asList(PlatformConstant.PROVINCE_PLATFORM, PlatformConstant.APP_PLATFORM, PlatformConstant.H5_2_PLATFORM, PlatformConstant.PLATFORM_H5, PlatformConstant.H5_3_PLATFORM);
                }
                else{
                    //区域渠道选择的省份集合
                    List<String> provinceCodes = Optional.ofNullable(request.getProvinceCodes()).orElse(new ArrayList<>());
                    if(PlatformConstant.PROVINCE_PLATFORM.equals(request.getPlatformData())){
                        for (String provinceCode : provinceCodes) {
                            platformDataList.add(PlatformConstant.PROVINCE_PLATFORM + provinceCode);
                        }
                    }else {
                        platformDataList.add(request.getPlatformData());
                    }
                }
                List<Product> channelProducts = channelProductService.queryBySupplyIdAndPlatformData(supplyProductIds, platformDataList);
                request.setProducts(channelProducts);
            }
        }
        PutOutProductResp putOutProductResp = channelProductService.batchPutOutChannelProduct(request.getProducts(),request.getStatus());
        return CommonResult.success(putOutProductResp);
    }

    /**
     * 选品中心-查询列表
     * @return
     */
    @PostMapping(value = "/findProduceSelect")
    public Object findProduceSelect(@RequestBody ChannelProductSelectRequest request) {
        return channelProductService.findProduceSelect(request);
    }

    /**
     * 选品中心-选品详情
     * @param productId
     * @return
     */
    @GetMapping("/getProductDetail/{productId}")
    public CommonResult getProductDetail(@PathVariable Integer productId) {
        ProductSelectDetailResponse productSelectDetail = channelProductService.findProductSelectDetail(productId);
        return CommonResult.success(productSelectDetail);
    }


    /**
     * 选品中心-批量放入仓库
     * @return
     */
    @PostMapping(value = "/selectAndAddProduces")
    public CommonResult selectAndAddProduces(@RequestBody com.ytjj.qmyx.admin.model.request.ChannelProductSelectRequest request) {
        return channelProductService.saveSelectedProducts(request.getIds(), request.getPlatformData(),request.getShopId(),request.getProvinceCodes()) ? CommonResult.success():CommonResult.failed();
    }

//    /**
//     * 地区渠道选品中心-批量放入仓库
//     * @return
//     */
//    @PostMapping(value = "/selectAndAddProducesForProvince")
//    public CommonResult selectAndAddProducesForProvince(@RequestBody com.ytjj.qmyx.admin.model.request.ChannelProductSelectRequest request) {
//        return channelProductService.saveSelectedProductsForProvince(request.getIds(), request.getPlatformData(),request.getShopId(),request.getProvinceCodes()) ? CommonResult.success():CommonResult.failed();
//    }

    /**
     * 地区渠道选品投放到指定地区
     * @return
     */
    @PostMapping(value = "/selectAndAddToProvince")
    public CommonResult selectAndAddToProvince(@RequestBody com.ytjj.qmyx.admin.model.request.ChannelProductSelectRequest request) {
        return channelProductService.selectAndAddToProvince(request.getIds(),request.getShopId(),request.getProvinceCodes()) ? CommonResult.success():CommonResult.failed();
    }

    /**
     * 复制商品
     */
    @GetMapping(value = "/copyProduct")
    public CommonResult<Integer> copyProduct(@RequestParam("id") Integer id) {
       Integer productId = channelProductService.copyProduct(id);
        return CommonResult.success(productId);
    }


    /**
     * 获取商品投放的地区
     * @param id 商品id
     * @param flag 1 一键上架标志 2-一键下架标志
     */
    @GetMapping(value = "/getProvinceByProductId")
    public CommonResult<List<SalesChannelsManagement>> getProvinceByProductId(Integer id, Integer flag) {
        List<SalesChannelsManagement> result = channelProductService.getProvinceByProductId(id, flag);
        return CommonResult.success(result);
    }


    /**
     * 销售渠道 - 商品分类
     * @return
     */
    @GetMapping(value = "/prodouctCategory")
    public CommonResult prodouctCategory() {
        return CommonResult.success(channelProductService.getAllProductCategorys());
    }

    /**
     * 同步分类菜单
     * @param :
     * @returns: com.ytjj.common.api.CommonResult
     * 
     */
    @GetMapping("/refreshProductCategory")
    public CommonResult refreshProductCategory(){
        channelProductService.refreshProductCategory();
        return CommonResult.success("开始后台同步");
    }

    /**
     * 测试更新商品
     * @param id:
     * @returns: com.ytjj.common.api.CommonResult
     * 
     */
    @GetMapping("/updateProd")
    public  CommonResult prodouctCategory(Integer id){
        return CommonResult.success("");
    }

    /**
     * 获取所有启用的销售渠道
     * @param type:渠道类型 1-平台 2-渠道 3-地区
     * @param flag:渠道标志 null-全部销售渠道 1-排除地区销售渠道外的所有渠道
     */
    @GetMapping("/getAllSalesChannels")
    public  CommonResult<List<SalesChannelsManagement>> getAllSalesChannels(Integer type,Integer flag){
        SalesChannelsManagement request = new SalesChannelsManagement();
        request.setStatus(1);
        request.setType(type);
        List<SalesChannelsManagement> allSalesChannels = channelProductService.getAllSalesChannels(request);
        if(flag != null && flag == 1){
            allSalesChannels = allSalesChannels.stream().filter(e -> !PlatformConstant.PROVINCE_PLATFORM.equals(e.getCode())).collect(Collectors.toList());
        }
        return CommonResult.success(allSalesChannels);
    }


    /**
     * 获取所有地区销售渠道
     */
    @GetMapping("/getAllAreaSalesChannels")
    public  CommonResult<List<SalesChannelsManagement>> getAllAreaSalesChannels(){
        SalesChannelsManagement request = new SalesChannelsManagement();
        request.setType(3);
        return CommonResult.success(channelProductService.getAllSalesChannels(request));
    }

    /**
     * 获取所有地区销售渠道列表详情
     */
    @GetMapping("/getSalesChannelsManagement")
    public CommonResult<AreaChannelsManagementResponse> getSalesChannelsManagement(Integer status){
        AreaChannelsManagementResponse salesChannelsManagement = channelProductService.getSalesChannelsManagement(status);
        return CommonResult.success(salesChannelsManagement);
    }

    /**
     * 新增或者修改地区销售渠道-地区
     */
    @PostMapping("/addOrUpdateArea")
    public CommonResult<AreaChannelsManagementResponse> addOrUpdateArea(@RequestBody SalesChannelsManagement request){
        Integer integer = channelProductService.addOrUpdateArea(request);
        return  integer > 0 ? CommonResult.success() : CommonResult.failed();
    }

    /**
     * 获取所有省份地区
     */
    @GetMapping("/getAllProvinceFromSupply")
    public CommonResult<List<Map<String, String>>> getAllProvinceFromSupply(){
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/banker/getProvince", null, supplyApiConfig.getHeadsMap());
        CommonResult commonResult = JSONObject.parseObject(resultJson, CommonResult.class);
        List<Map> maps = JSON.parseArray(JSON.toJSONString(commonResult.getData()), Map.class);
        List<Map<String, String>> collect = maps.stream().map(e -> {
            Map<String, String> map = new HashMap<>();
            map.put("code", e.get("pid").toString());
            map.put("name", e.get("name").toString());
            return map;
        }).collect(Collectors.toList());
        return CommonResult.success(collect);
    }



}
